package com.example.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: 15489  <br/>
 * Date: 2022/3/24:11:34  <br/>
 * Description:
 */

@RestController
@RequestMapping("/kill")
public class KillController3 {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private Redisson redisson;

    @GetMapping("/start3")
    public boolean start(){
//        用老保存秒杀的结果 false表示失败 true表示成功
        boolean flag=false;

//        设置一把锁
        String lock="woniuxy";

//        得到锁 分布式锁
        RLock rLock=redisson.getLock(lock);

//        获取库存 删减库存
        try {
//            加锁
            rLock.lock();
            int num=(Integer)redisTemplate.opsForValue().get("num");
            if(num>0){
                num--;
                System.out.println("删减库存成功还剩"+num);
                redisTemplate.opsForValue().set("num",num);

                flag=true;
            }
        }finally {
            rLock.unlock();
        }

        return flag;
    }
}
